package com.jh.fcsm.util.word;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class IOUtils {

    /***
     * 通过GET获取响应字符串
     * @param url
     * @return
     */
    public static String getStringGET(String url) throws IOException {
        String res = "";

        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        try(CloseableHttpClient httpClient = HttpClientBuilder.create().build()){
            // 创建Get请求
            HttpGet httpGet = new HttpGet(url);
            // 响应模型
            // 由客户端执行(发送)Get请求
            try(CloseableHttpResponse response = httpClient.execute(httpGet)) {

                // 从响应模型中获取响应实体
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    res = EntityUtils.toString(responseEntity);
                }
            } catch (IOException e) {
                throw e;
            }
        } catch (IOException e) {
            throw e;
        }

        return res;
    }

    /***
     * 通过GET读取文件并装换未字节
     * @param url
     * @return
     */
    public static byte[] getByteGET(String url) throws IOException {
        if (url.startsWith("http")) {
            return getByteFromNet(url);
        } else {
            return FileUtils.InputStream2ByteArray(url);
        }
    }

    private static byte[] getByteFromNet(String url) throws IOException {
        byte[] bytes = null;
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        try(CloseableHttpClient httpClient = HttpClientBuilder.create().build()){
            // 创建Get请求
            HttpGet httpGet = new HttpGet(url);
            // 响应模型
            // 由客户端执行(发送)Get请求
            try(CloseableHttpResponse response = httpClient.execute(httpGet)) {
                // 从响应模型中获取响应实体
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    bytes = EntityUtils.toByteArray(response.getEntity());
                }
            } catch (IOException e) {
                throw e;
            }
        } catch (IOException e) {
            throw e;
        }
        return bytes;
    }
}
